package com.shushan.accessibility;

import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.permission.FloatPermissionUtil;
import com.android.permission.rom.RomType;
import com.android.permission.rom.RomUtils;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.manager.JobSchedulerManager;
import com.shushan.permission.BackgroundPermissionActivity;
import com.shushan.permission.OpenCompleteActivity;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.permission.OpenWindowActivity;
import com.shushan.permission.PowerManagerActivity;
import com.shushan.receiver.LockAdminReceiver;
import com.shushan.service.DaemonService;
import com.shushan.service.PlayerMusicService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;

/**
 * @ClassName: PermissionHandOpenActivity
 * @Desciption: 手动权限设置
 * @author: yichaohua
 * @date: 2018-07-18
 */
public class PermissionHandOpenActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "PermissionHandOpenActivity";

    private boolean isBackground = true;
    private boolean isOpenComplete = false;
    private boolean isOpneWindow = false;
    private boolean isUsageable = false;
    private boolean isAdminEnable = false;
    private boolean isPowerClose = false;

    private RelativeLayout backgroundLayout;
    private RelativeLayout completeLayout;
    private RelativeLayout windowLayout;
    private RelativeLayout usageableLayout;
    private RelativeLayout adminEnableLayout;
    private RelativeLayout powerCloseLayout;

    private Button backgroundButton;
    private Button completeButton;
    private Button windowButton;
    private Button usageableButton;
    private Button adminEnableButton;
    private Button powerCloseButton;
    private Button finishButton;

    private ImageView backgroundImg;
    private ImageView completeImg;
    private ImageView windowImg;
    private ImageView usageableImg;
    private ImageView adminEnableImg;
    private ImageView powerCloseImg;

    private TextView powerCloseText;

    private RomType romType;

    private DevicePolicyManager dpm;
    private ComponentName adminComponent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.permission_hand_open_activity);

        ScreenManager sm = new ScreenManager();
        sm.setDeepStatusBar(true,this);

        dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
        adminComponent = new ComponentName(this, LockAdminReceiver.class);

        romType = RomUtils.getRomType(this);
        Log.i(TAG,"romType=" + romType.toString());

        isOpenComplete = getIntent().getBooleanExtra("isOpenComplete",false);
        isOpneWindow = getIntent().getBooleanExtra("isOpneWindow",false);
        isUsageable = getIntent().getBooleanExtra("isUsageable",false);
        isAdminEnable = getIntent().getBooleanExtra("isAdminEnable",false);
        isPowerClose = getIntent().getBooleanExtra("isPowerClose",false);

        initView();

        initData();
    }

    private void initView() {
        powerCloseText = findViewById(R.id.permission_hand_power_close_tv);
        powerCloseLayout = findViewById(R.id.permission_hand_power_close_layout);
        completeLayout = findViewById(R.id.permission_hand_complete_layout);
        windowLayout = findViewById(R.id.permission_hand_window_layout);
        usageableLayout = findViewById(R.id.permission_hand_usageable_layout);
        adminEnableLayout = findViewById(R.id.permission_hand_admin_enable_layout);
        backgroundLayout = findViewById(R.id.permission_hand_background_layout);

        backgroundButton = findViewById(R.id.permission_hand_background_btn);
        backgroundButton.setOnClickListener(this);
        completeButton = findViewById(R.id.permission_hand_complete_btn);
        completeButton.setOnClickListener(this);
        windowButton = findViewById(R.id.permission_hand_window_btn);
        windowButton.setOnClickListener(this);
        usageableButton = findViewById(R.id.permission_hand_usageable_btn);
        usageableButton.setOnClickListener(this);
        adminEnableButton = findViewById(R.id.permission_hand_admin_enable_btn);
        adminEnableButton.setOnClickListener(this);
        powerCloseButton = findViewById(R.id.permission_hand_power_close_btn);
        powerCloseButton.setOnClickListener(this);
        finishButton = findViewById(R.id.permission_hand_finish_btn);
        finishButton.setOnClickListener(this);

        backgroundImg = findViewById(R.id.permission_hand_background_img);
        powerCloseImg = findViewById(R.id.permission_hand_power_close_img);
        completeImg = findViewById(R.id.permission_hand_complete_img);
        windowImg = findViewById(R.id.permission_hand_window_img);
        usageableImg = findViewById(R.id.permission_hand_usageable_img);
        adminEnableImg = findViewById(R.id.permission_hand_admin_enable_img);
    }

    private void initData() {
        if(romType == RomType.FUNTOUCHOS_ROM && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            isBackground = false;
            backgroundLayout.setVisibility(View.VISIBLE);
        }

        if(isOpenComplete){
            completeLayout.setVisibility(View.GONE);
        }

        if(isOpneWindow){
            windowLayout.setVisibility(View.GONE);
        }

        if(isUsageable){
            usageableLayout.setVisibility(View.GONE);
        }

        if(isAdminEnable){
            adminEnableLayout.setVisibility(View.GONE);
        }

        if(isPowerClose){
            powerCloseLayout.setVisibility(View.GONE);
        }else if(romType == RomType.SMARTISAN_ROM){
            powerCloseText.setText("开启后台常驻");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.permission_hand_background_btn:
                startActivityForResult(BackgroundPermissionActivity.class);
                break;
            case R.id.permission_hand_complete_btn:
                startActivityForResult(OpenCompleteActivity.class);
                break;
            case R.id.permission_hand_window_btn:
                startActivityForResult(OpenWindowActivity.class);
                break;
            case R.id.permission_hand_usageable_btn:
                startActivityForResult(OpenUsageActivity.class);
                break;
            case R.id.permission_hand_admin_enable_btn:
                checkAndEnableAdmin();
                break;
            case R.id.permission_hand_power_close_btn:
                startActivityForResult(PowerManagerActivity.class);
                break;
            case R.id.permission_hand_finish_btn:
                onFinishSet();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    private void checkAndEnableAdmin() {
        if (!dpm.isAdminActive(adminComponent)) {
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminComponent);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, this.getString(R.string.device_admin_hint));
            startActivityForResultAllow(intent, 150);
        } else {
            Log.i(TAG,"设备管理器已激活");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.i(TAG,"onActivityResult requestCode=" + requestCode + " resultCode=" + resultCode);

        if(requestCode == 150){
            if (dpm.isAdminActive(adminComponent)) {
                isAdminEnable = true;
                adminEnableButton.setVisibility(View.GONE);
                adminEnableImg.setVisibility(View.VISIBLE);
            }
        }else {
            if(resultCode == 200){
                isOpenComplete = true;
                completeButton.setVisibility(View.GONE);
                completeImg.setVisibility(View.VISIBLE);
            }else if(resultCode == 300){
                RomType romType = RomUtils.getRomType(this);
                if(!(romType == RomType.FUNTOUCHOS_ROM || romType == RomType.SMARTISAN_ROM)){
                    if(FloatPermissionUtil.checkPermission(this)){
                        isOpneWindow = true;
                        windowButton.setVisibility(View.GONE);
                        windowImg.setVisibility(View.VISIBLE);
                    }else {
                        isOpneWindow = false;
                        windowButton.setVisibility(View.VISIBLE);
                        windowImg.setVisibility(View.GONE);
                    }
                }else {
                    isOpneWindow = true;
                    windowButton.setVisibility(View.GONE);
                    windowImg.setVisibility(View.VISIBLE);
                }


            }else if(resultCode == 500){
                isPowerClose = true;
                powerCloseButton.setVisibility(View.GONE);
                powerCloseImg.setVisibility(View.VISIBLE);
            }else if(resultCode == 600){
                if(SystemUtils.checkUsagePermission(this)){
                    isUsageable = true;
                    usageableButton.setVisibility(View.GONE);
                    usageableImg.setVisibility(View.VISIBLE);
                }else {
                    isUsageable = false;
                    usageableButton.setVisibility(View.VISIBLE);
                    usageableImg.setVisibility(View.GONE);
                }
            }else if(resultCode == 700){
                isBackground = true;
                backgroundButton.setVisibility(View.GONE);
                backgroundImg.setVisibility(View.VISIBLE);
            }
        }

    }

    private void onFinishSet() {
        if(isBackground && isOpenComplete && isOpneWindow && isUsageable
                && isAdminEnable && isPowerClose){

            SharedPreferencesUtils.setBooleanDate(Constants.MAIN_PERMISSION_HAS_SET_SHAREPREFERS_KEY,true);
            SharedPreferencesUtils.setBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY,true);

            SharedPreferencesUtils.setBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY,true);
            Intent intent = new Intent(this, DaemonService.class);
            startService(intent);

            Intent intent1 = new Intent(this,PlayerMusicService.class);
            startService(intent1);

            //启动系统任务
            JobSchedulerManager mJobManager = JobSchedulerManager.getJobSchedulerInstance(BabyApplication.getInstance());
            mJobManager.startJobScheduler();

            onBackAction();
        }else {
            showWindowWarnDialog();
        }
    }

    private void showWindowWarnDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未完成权限设置，是否退出设置？")
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        onBackAction();

                    }
                })
                .setPositiveButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .create().show();
    }
}
